/**
 * @author klv
 */
var ShareModule = function(){
    this.shareobj = {};
    this.sharetype = "";
    this.widgetID="";
	this.workspaceID="";
	this.msg=null;
	this.cacheShare={};
};
ShareModule.prototype = {
    send: function(type,wsid,widgetid,receive,subject,message,callback){
		this.sharetype=type;//0:workspace;1:widget
		this.widgetID=widgetid;
		this.workspaceID=wsid;
        var strDetail = this._generateShare();
		var self=this;
		if (!strDetail){
	        Util.message(QS_Lang.text["sharefailed"]); 
			return {status:false};
		}else {
			DBHelper.sendShare({
                senderAddress:QS_UserNAME,
                receiverAddress:receive.join(','),
                messageType:this.sharetype, 
                subject:subject,
                content:message,
                sharingContent:strDetail
            },function(o){
                self._defaultCallback(o,callback);
            });
		}
    },
	_defaultCallback:function(o,callback){
		var o=o.replace(/\r\n/g, "");
        if ($.trim(o) != '') {
            o = $.evalJSON(o);
        }
        else{
            o={};
        }
        if(o.error&&o.error.length>0){
            var errorDetail="";
            for(var i=0,l=o.error.length;i<l;i++){
                //o.error[i].email,o.error[i].code
                errorDetail+=String.format("{0}<br \>",o.error[i].email);
            }
            var errorstr="The following recipient(s) cannot be reached";
            Util.message(String.format("{0}:{1}",errorstr,errorDetail));
        }
        if(callback){
            callback(o)
        }else{
			return o;
		}
	},
	getShareData:function(shareid,callback){
		var self=this;
		if (!this.cacheShare[shareid]) {
			DBHelper.getShareData({
				shareid: shareid
			}, function(o){
				var result = self._defaultCallback(o);
				if (!result.content) {
					Util.message(String.format("Sorry,shared content(shareid:{0}) lose.", shareid));
				}
				else {
					var content=$.evalJSON(result.content);
					self.cacheShare[shareid]={content:content,sharingType:result.sharingType};
					if (callback) {
						callback(content);
					}
				}
			});
		}else{
			if (callback) {
                callback(this.cacheShare[shareid].content);
            }
		}
	},
	getShareType:function(shareid,callback){
		if (!this.cacheShare[shareid]) {
	        DBHelper.getShareData({
	            shareid: shareid
	        }, function(o){
	            var result = self._defaultCallback(o);
	            if (!result.sharingType) {
	                Util.message(String.format("Sorry,shared type(shareid:{0}) lose.", shareid));
	            }
	            else {
	                var content=$.evalJSON(result.content);
	                self.cacheShare[shareid]={content:content,sharingType:result.sharingType};
	                if (callback) {
	                    callback(result.sharingType);
	                }
	            }
	        });
	    }else{
	        if (callback) {
	            callback(this.cacheShare[shareid].sharingType);
	        }
	    }
	},
	openShared:function(msg,currentWS){
		//shareType,shareid
		this.msg = msg;
		if(!this.Filter){
			this.Filter=new FilterForShare();
		}
		var shareType=this._getMessageType();
		var shareID=this._getShareID();
		if(shareType==null||shareID==null){
			Util.message(QS_Lang.text["sharefailed"]);
		}else{
			if (shareType) {
				this.openSharedWorkspace(shareID);
			}
			else {
				//open saved wigdets
				this.openSharedWigdets(shareID, currentWS);
			}
		}
	},
	_getMessageType:function(){
		var returnValue=null,msg=this.msg;
		if(!msg||$.isEmptyObject(msg)) return returnValue;
		var msgType=msg["messageType"];
		if(msgType==1){
			if (typeof(msg['attachment']) != 'undefined' && msg['attachment'].indexOf(',') != -1) {
				var attachment = msg['attachment'].split(',');
				if (attachment[1] && attachment[1] == '0') {
					//workspace
					returnValue=true;
				}else {
					//widget
					returnValue=false;
				}
			}
		}
		return returnValue;
	},
	_getShareID:function(){
		var returnValue=null,msg=this.msg;
		if(!msg||$.isEmptyObject(msg)) return returnValue;
		if (typeof(msg['attachment']) != 'undefined' && msg['attachment'].indexOf(',') != -1) {
			var attachment = msg['attachment'].split(',');
			returnValue=attachment[0];
		}
		return returnValue;
	},
	_getMessageDate:function(){
		var returnValue=null,msg=this.msg;
		if(!msg||$.isEmptyObject(msg)) return returnValue;
		if (msg['createTime']) {
			returnValue=msg['createTime'].split(' ')[0];
		}
		return returnValue;
	},
    openSharedWigdets: function(shareid, current){
        //get data from db
		var self=this;
        this.getShareData(shareid,function(widget){
			var strDetail=$.extend(true,{},widget);
			var id = idService.newMinusId(),tab=null;
			strDetail.id = id;
			if (!current) {
				gWsList[id] = {
					id: id,
					profile: {
						name: "Untitled",
						showHelper: false
					}
				};
				wsWidgets[id] = [];
				tab = workspaceManager.createWorkSpace(gWsList[id]);
				tab.active();
			}
			self.Filter.widget(strDetail.profile.type).share(strDetail,false,function(config){RtqDesktop.createModule(config,tab);});
		});
    },
    openSharedWorkspace: function(shareid){
        //get data from shareid
		var self=this;
        this.getShareData(shareid,function(workspace){
			var workspaceObj=$.extend(true,{},workspace);
			var id = idService.newMinusId();
			gWsList[id] = {
				id: id,
				profile: {
					name: workspaceObj.name,
					showHelper: false
				}
			};
			wsWidgets[id] = [];
			/* old code
			if (workspaceManager.hasWorkspaceName(workspaceObj.name)) {
				Util.confirm(String.format(QS_Lang.text["opensharerenamews"],workspaceObj.name), function(b){
						if (b) {
							gWsList[id].profile.name = "Untitled";
							wsWidgets[id] = [];
							var tab = workspaceManager.createWorkSpace(gWsList[id]);
							tab.active();
							self._openWorkspaceWidgets(workspaceObj.widgets,function(returnconfig){RtqDesktop.createModule(returnconfig,tab);});
						}
				}, {
					title: 'Share Workspace'
				});		
			}
			*/
			var tab = workspaceManager.createWorkSpace(gWsList[id]);
			tab.active();
			self._openWorkspaceWidgets(workspaceObj.widgets,function(returnconfig){
				RtqDesktop.createModule(returnconfig,tab);
			});
		});
    },
	_openWorkspaceWidgets:function(configs,callback){
		if(configs.length==0) return;
	    var config=configs.shift(),self=this;
		with({"subConfigs":configs}){
			this.Filter.widget(config.profile.type).share(config,false,function(returnconfig){ 
				if(callback){
					callback(returnconfig);
				}
				self._openWorkspaceWidgets(subConfigs,callback);
			});
		}
	},
    _generateShare: function(){
		this.shareobj={};
        if (this.sharetype == "0") {
            if (!this.workspaceID) {
				Util.message(QS_Lang.text["shareerror"]);
				return null;
			}
			this.shareobj.name = gWsList[this.workspaceID]?gWsList[this.workspaceID].profile.name:"";
            this.shareobj.widgets = [];
			var widgets=workspaceManager.getTabWidgets().widgets.list;
			$.merge(this.shareobj.widgets, widgets);
        }
        else {
			if (!this.widgetID||!this.workspaceID) {
				Util.message(QS_Lang.text["shareerror"]);
				return null;
			}
            var widgets = wsWidgets[this.workspaceID],widget=WorkspaceTabs.currentTab.modules[this.widgetID].win.widget;
            for (var i = 0; i < widgets.length; i++) {
                if (widgets[i].id == this.widgetID) {
                    $.extend(true, this.shareobj, widgets[i]);// layout config
                    break;
                }
            }
			if(widget&&widget.saveConfig){
				$.extend(true, this.shareobj,{profile:{widget:widget.saveConfig()}});// widget config
			}
        }
        return this._filterData();
        //insert to db
    },
	_clear:function(){
		for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
	},
    _filterData: function(){
		if(!this.Filter){
			this.Filter=new FilterForShare();
		}
        if (this.sharetype == "0") {//workspace
            for (var i = 0; i < this.shareobj.widgets.length; i++) {
                this.Filter.widget(this.shareobj.widgets[i].profile.type).filter(this.shareobj.widgets[i]);
            }
        }
        else {
            delete this.shareobj.id;
			this.Filter.widget(this.shareobj.profile.type).filter(this.shareobj);
        }
        return $.toJSON(this.shareobj);
    }
}
var QS_ShareModule=null;

var FilterForShare=function(){
	var viewName="Share:{0}";
	var _addFilterCommon=function(config){
		if(config.profile.name){
			var name=config.profile.name.split(":")[0];
			config.profile.name=name;
		}
	};
	// it is necessary
	var _addWidgetInfo=function(config){
		config.id = idService.newMinusId();//new id
	};
	var _getSavedView=function(cols){
        var viewK = [];
        for(var i=0;i<cols.length;i++){
            var vk = {};
            vk.dataIndex = cols[i].dataIndex;
            if(cols[i].width)vk.width = cols[i].width;
            viewK.push(vk);
        }
        return viewK;
    };
	var filterWL=function(config){
		//set: can be shared
		var defaultShareConfig={
								profile:{
											widget:{currentId:"0",openedList:[{"id":"0"}]}
										}
							  };//default infomation
		delete config.profile.widget.openedList;//cancel the openedList
		if(config.profile.widget.windowConfig.isSelectTabName){//change the name
			config.profile.name=QS_Lang.watchlist["txt"]["startupName"];
		}
		if(config.profile.widget.colsViewID>0){//save the customview
			if(QS_CustomViewManagement){
				var veiwData=QS_CustomViewManagement.getCustomviewData(config.profile.widget.colsViewID);
				config.profile.share ={title:veiwData.data.title,cols:_getSavedView(veiwData.data.cols)};
			}
		}
		_addFilterCommon(config);
		$.extend(true,config,defaultShareConfig);
		return config;
	};
	var shareWL=function(config,again,callback){
		_addWidgetInfo(config);
		var iteration=again||false;
		if(!$.isEmptyObject(config.profile.share)){
			var shareObj=config.profile.share,self=this;
			if(QS_CustomViewManagement){
				var title=shareObj.title,newName=String.format(viewName,title);
				QS_CustomViewManagement.getCustomviewList(function(){
					var cols=shareObj.cols,index=QS_CustomViewManagement.getShareViewMaxIndex(title);
					if(!QS_CustomViewManagement.checkName(newName)||index>0){
						index=index+1;
					}
					if(index>0){
						newName=String.format("{0}_{1}",newName,index);
					}
					/* old code
					if(!iteration){
						Util.message(QS_Lang.text["sharewatchlist"]);
					}
					Util.prompt(QS_Lang.text["watchlistinput"], function(name){
						var name = $.trim(name);
						shareWL($.extend(true,config,{profile:{share:{title:name}}}),true,callback);
					},{
						validateMethod: function(value){
							if($.trim(value)==""){
								Util.message(QS_Lang.text["watchlistcvinput"]);
								return false;
							}
							if(!QS_Validator.test(value, 'name')){
								return false;								
							}
							if(!QS_CustomViewManagement.checkName(value)){
								Util.message(QS_Lang.text["watchlistcvtitle"]);
								return false;
							}
							return true;
						},
						cancelCallBack: function(){
							shareWL($.extend(true,config,{profile:{share:{title:shareObj.title+prefix+new Date().getTime()}}}),true,callback);
						}
					});
					*/
					QS_CustomViewManagement.addCustomView(newName,cols,function(d){
						config.profile.widget.colsViewID=d;
						delete config.profile.share;
						if(callback){
							callback(config);
						}
					});
				});
			}else{
				if(callback){
					delete config.profile.share;
					callback(config);
				}
			}
		}else{
			if(callback){
				callback(config);
			}
		}
	};
	var filterNews=function(config){
		//set: can be shared
		var defaultShareConfig={
								profile:{   
											widget:{ticker:null,title:name}//0P0000RYUS
										}
							  };//default infomation
		if(config.profile.widget.currentViewID>0){//save the customview
			if(GB_NewsDataManager){
				config.profile.share = GB_NewsDataManager.getViewSourceById(config.profile.widget.currentViewID,config.profile.widget.type,null);
			}
		}
		var openlist=config.profile.widget.openedList;
		for(var i=openlist.length-1;i>=0;i--){
			if(openlist[i]>0){
				config.profile.widget.openedList.splice(i,1);
			}
		}
		_addFilterCommon(config);
		$.extend(true,config,defaultShareConfig);
		return config;
	};
	var shareNews=function(config,again,callback){
		_addWidgetInfo(config);
		var iteration=again||false;
		if(!$.isEmptyObject(config.profile.share)){
			var shareObj=config.profile.share,self=this,type=config.profile.widget.type;
			if(GB_NewsCustomView&&GB_NewsDataManager){
				GB_NewsDataManager.getViewList(type,function(){
					var title=shareObj.title,newName=String.format(viewName,title),index=GB_NewsCustomView.getShareViewMaxIndex(type,title);
					if(!GB_NewsCustomView.checkName(type,newName)||index>0){
						index=index+1;
					}
					if(index>0){
						newName=String.format("{0}_{1}",newName,index);
					}
					/*old code
					if(!iteration){
						Util.message(QS_Lang.text["sharenews"]);
					}
					Util.prompt(QS_Lang.text["watchlistinput"], function(name){
							var name = $.trim(name);
							shareNews($.extend(true,config,{profile:{share:{title:name}}}),true,callback);
						},{
							validateMethod: function(value){
								if($.trim(value)==""){
									Util.message(QS_Lang.text["watchlistcvinput"]);
									return false;
								}
								if(!QS_Validator.test(value, 'name')){
									return false;
								}									
								if(!GB_NewsCustomView._checkName(value)){
									Util.message(QS_Lang.text["newssamename"]);
									return false;
								}
								return true;
							},
							cancelCallBack: function(){
								shareNews($.extend(true,config,{profile:{share:{title:shareObj.title+prefix+new Date().getTime()}}}),true,callback);
							}
					});
					*/
					shareObj.title=newName;
					GB_NewsDataManager.createViewSource(shareObj,function(id){
						if(id>0){
							delete config.profile.share;
							config.profile.widget.openedList.push(id);
							config.profile.widget.currentViewID=id;
							if(callback){
								callback(config);
							}
						}
					});
				});
			}else{
				if(callback){
					delete config.profile.share;
					callback(config);
				}
			}
		}else{
			if(callback){
				callback(config);
			}
		}
	};
	var filterChart=function(config){
		//set: can be shared
		var defaultShareConfig={
								profile:{   
											widget:{mTicker:null,title:name}//0P0000RYUS
										}
							  };//default infomation
		_addFilterCommon(config);
		$.extend(true,config,defaultShareConfig);
		return config;
	};
	var filterQT=function(config){
		//set: can be shared
		var defaultShareConfig={
								profile:{   
											widget:{secId:"",ticker:""}//0P0000RYUS
										}
							  };//default infomation
		_addFilterCommon(config);
		$.extend(true,config,defaultShareConfig);
		return config;
	};
	var filterRS=function(config){
		//set: can be shared
		var name=config.profile.widget.title.split(":")[0],defaultShareConfig={
								profile:{   
											widget:{
												ticker:"",
												title:name,
												cpnConfig:{
													ticker:""//0P0000RYUS
												}
											}
										}
							  };//default infomation
		var cpnConfig=config.profile.widget.cpnConfig,tempSub;
		for(var sub in cpnConfig){
			if(!cpnConfig[sub]) continue;
			if(cpnConfig[sub].secId){//quote
				cpnConfig[sub].secId="";
			}
			if(cpnConfig[sub].mTicker){//chart
				cpnConfig[sub].mTicker="";
			}
			if(cpnConfig[sub].ticker){//news,quote
				cpnConfig[sub].ticker=null;
			}
		}
		_addFilterCommon(config);
		$.extend(true,config,defaultShareConfig);
		return config;
	};
	var filterDefault=function(config){
		var defaultShareConfig={
								profile:{   
											widget:{ticker:''}//0P0000RYUS
										}
							  };//default infomation
		_addFilterCommon(config);
		$.extend(true,config,defaultShareConfig);
		return config;
	};

	var shareDefault=function(config,again,callback){
		_addWidgetInfo(config);
		callback(config);
	};
	var filterConfig={
		"0":{filter:filterWL,share:shareWL},//WatchlistWindow
		"1":{filter:filterChart,share:shareDefault},//ChartWindow
		"2":{filter:filterNews,share:shareNews},//NewsWindow
		"3":{filter:filterQT,share:shareDefault},//QtWindow
		"9":{filter:filterRS,share:shareDefault},//ResearchWindow
		"999":{filter:filterDefault,share:shareDefault}
	 };
	return {
		widget:function(type){
			return filterConfig[type]?filterConfig[type]:filterConfig["999"];
		}
	};
}

